import React, { useMemo } from 'react';
import {
  Modal,
  Form,
  Select,
  InputNumber,
  TreeSelect,
  DatePicker,
  Row,
  Col,
  Upload,
  Button,
} from 'antd';
import { OrganizationItem } from 'admin/schema/Cas';
import { convertToTree, downLoadByUrl } from '../utils';
import { uploadUrl } from 'admin/servers/servers';
import { UploadOutlined } from '@ant-design/icons';
import { filter, get, map } from 'lodash';
import { useSelector } from 'react-redux';

interface Props {
  visible: boolean;
  title: string;
  onOk: () => void;
  onCancel: () => void;
  form: any;
  abilityType: string[];
  orgTree: Omit<OrganizationItem, 'children' | 'description'>[];
}

const AbilityFormModal: React.FC<Props> = ({
  visible,
  title,
  onOk,
  onCancel,
  form,
  orgTree,
  abilityType,
}) => {
  const uniqueToken = useSelector((state: any) => state.uniqueToken);
  const userInfo = useSelector((state: any) => state.loginInfo);
  const treeData = useMemo(() => {
    const treeData = convertToTree(filter(orgTree, { pid: '0' }));
    return treeData;
  }, [orgTree]);

  return (
    <Modal
      title={title}
      visible={visible}
      onOk={onOk}
      onCancel={onCancel}
      width={600}
      maskClosable={false}
      destroyOnClose
    >
      <Form form={form} layout="vertical">
        <Row gutter={24}>
          <Col span={12}>
            <Form.Item name="type" label="类型" rules={[{ required: true, message: '请选择类型' }]}>
              <Select placeholder="请选择类型">
                {map(abilityType, item => (
                  <Select.Option key={item} value={item}>
                    {item}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              style={{ margin: 0 }}
              shouldUpdate={(prevValues, currentValues) => prevValues.type !== currentValues.type}
            >
              {({ getFieldValue }) => (
                <Form.Item
                  name="quantity"
                  label={`数量(${getFieldValue('type') === '智能外呼' ? '分钟' : '条'})`}
                  tooltip={{
                    title: (
                      <>
                        <strong>行业短信/靶向短信：</strong>
                        根据通信格式规范，单条信息容量上限为70字符（含空格及标点）。当内容超过此限制时，系统将自动分段传送并按照实际拆分条数计费。例如130字符信息将拆分为两条计收费用，建议合理规划内容长度。
                        <br />
                        <strong>智能外呼：</strong>通话按分钟计费（不足1分钟按整分钟算）
                      </>
                    ),
                    placement: 'top',
                  }}
                  rules={[{ required: true, message: '请输入数量' }]}
                >
                  <InputNumber
                    formatter={value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                    parser={value => value?.replace(/\$\s?|(,*)/g, '') as any}
                    style={{ width: '100%' }}
                    min={1}
                    placeholder="请输入数量"
                  />
                </Form.Item>
              )}
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={24}>
          <Col span={12}>
            <Form.Item name="org" label="单位" rules={[{ required: true, message: '请选择单位' }]}>
              <TreeSelect
                showSearch
                style={{ width: '100%' }}
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                placeholder="请选择单位"
                allowClear
                fieldNames={{ label: 'name', value: 'id', children: 'children' }}
                treeData={treeData}
                treeNodeFilterProp="title"
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="threshold"
              label="阈值"
              tooltip={{
                title: '当使用数量达到设置百分比时，将进行消息提示',
                placement: 'top',
              }}
              rules={[
                { required: true, message: '请输入阈值' },
                { type: 'number', min: 0, max: 100, message: '阈值必须在0到100之间' },
              ]}
            >
              <InputNumber style={{ width: '100%' }} min={0} max={100} step={1} addonAfter="%" />
            </Form.Item>
          </Col>
        </Row>

        {/* 年份 与 阈值 */}
        <Row gutter={24}>
          <Col span={12}>
            <Form.Item name="year" label="年份" rules={[{ required: true, message: '请选择年份' }]}>
              <DatePicker
                style={{ width: '100%' }}
                picker="year"
                placeholder="请选择年份"
                disabledDate={date => date.isBefore(new Date())}
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="materials"
              label="证明材料"
              tooltip={{
                title:
                  '只支持业务类，不支持宣发类 1.业务使用场景，发送对象人群 2.申请能力数据数量的测算依据 3.需加盖公章',
                placement: 'top',
              }}
              rules={[{ required: true, message: '请上传证明材料' }]}
              valuePropName="fileList"
              getValueFromEvent={e => {
                if (Array.isArray(e)) {
                  return e;
                }
                return e && e.fileList;
              }}
              extra={
                <div style={{ display: 'flex', flexDirection: 'column' }}>
                  <a href="/webapp/模板-西安市综合短信发布平台能力申请表.pdf" target="_blank">
                    模板-西安市综合短信发布平台能力申请表.pdf
                  </a>
                </div>
              }
            >
              <Upload
                name="files"
                action={uploadUrl}
                headers={{
                  uniqueToken,
                  userId: userInfo.id,
                }}
                showUploadList={{
                  showPreviewIcon: false,
                  showDownloadIcon: true,
                }}
                onDownload={(file: any) => {
                  downLoadByUrl(
                    get(file, 'response.data[0].path'),
                    get(file, 'response.data[0].realName')
                  );
                }}
              >
                <Button icon={<UploadOutlined />}>上传证明材料</Button>
              </Upload>
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
};

// 使用 React.memo 优化组件性能
export default React.memo(AbilityFormModal);
